package eom.example.elasticsearch.controller;

import bom.example.common.common.Results;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.core.metadata.IPage;
import eom.example.elasticsearch.domain.CmsContent;
import eom.example.elasticsearch.domain.Student;
import eom.example.elasticsearch.domain.vo.CmsContentVo;
import eom.example.elasticsearch.service.CmsContentService;
import eom.example.elasticsearch.utils.ElasticSearchUtils;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author X.I.O
 * @title: CmsController
 * @projectName spring-boot-elasticsearch
 * @description: TODO
 * @date 2021/11/19 9:46
 */
@RestController
@RequestMapping("/content")
public class CmsController {

    private static final String INDEX_NAME="content";

    @Autowired
    private CmsContentService cmsContentService;

    @Autowired
    private ElasticSearchUtils elasticSearchUtils;

    @PostMapping("add")
    @ApiOperation("内容添加")
    public JSONObject addController(@RequestBody @Validated CmsContentVo cmsContentVo){
        CmsContent cmsContent=new CmsContent();
        BeanUtils.copyProperties(cmsContentVo,cmsContent);
        cmsContentService.save(cmsContent);
        return Results.success();
    }

    @PostMapping("page")
    @ApiOperation("内容分页")
    public JSONObject pageSearchController(@ApiParam("页码") @RequestParam(value = "pageNum",defaultValue = "1")Integer page,
                                             @ApiParam("条数")@RequestParam(value = "pageSize",defaultValue = "10")Integer size,
                                             @ApiParam("关键字")@RequestParam(value = "keyword",required = false)String keyword){
        IPage<CmsContent> contentIPage=cmsContentService.pageCmsContent(page,size,keyword);
        return Results.success(contentIPage.getRecords(),contentIPage.getTotal());
    }

    @PostMapping("updata")
    @ApiOperation("内容更新")
    public JSONObject contentController(@RequestBody CmsContent cmsContent){
        if(cmsContent==null || cmsContent.getId()==null){
            return Results.error("必要参数不得为空");
        }
        CmsContent cmsContent1=cmsContentService.getById(cmsContent.getId());
        if(cmsContent1==null){
            return Results.error("请刷新系统后重试");
        }
        cmsContentService.updateById(cmsContent);
        return Results.success();
    }

    @PostMapping("getOne/{id}")
    @ApiOperation("通过id获取一个")
    public JSONObject getOneController(@ApiParam("请求id")@PathVariable("id")Integer id){
        CmsContent cmsContent=cmsContentService.getById(id);
        return Results.success(cmsContent);
    }

    @ApiOperation("批量添加到es")
    @PostMapping("addEs")
    public JSONObject addEsController() throws Exception{
       boolean flag=elasticSearchUtils.exitIndex(INDEX_NAME);
       if(!flag){
           elasticSearchUtils.createIndex(INDEX_NAME);
       }
       List<CmsContent> cmsContents=cmsContentService.list();
       elasticSearchUtils.addList(cmsContents,INDEX_NAME);
       return Results.success();
    }

    @ApiOperation("es搜索")
    @PostMapping("esSearch")
    public JSONObject esSearchController(@ApiParam("页码")@RequestParam(value = "page",defaultValue = "1")Integer page,
                                         @ApiParam("条数")@RequestParam(value = "size",defaultValue = "10")Integer size,
                                         @ApiParam("关键字")@RequestParam(value = "keyword",required = false)String keyword) throws Exception{
        //创建搜索的builder
        SearchSourceBuilder builder=new SearchSourceBuilder();
        //创建条件构造器
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        if(StringUtils.isNotBlank(keyword)){
            MatchPhraseQueryBuilder title_name = QueryBuilders
                    .matchPhraseQuery("titleName", keyword);
            boolQueryBuilder.should(title_name);

            MatchPhraseQueryBuilder tags = QueryBuilders
                    .matchPhraseQuery("tags", keyword);
            boolQueryBuilder.should(tags);


            MatchPhraseQueryBuilder author = QueryBuilders
                    .matchPhraseQuery("author", keyword);
            boolQueryBuilder.should(author);

            MatchPhraseQueryBuilder sub_title = QueryBuilders
                    .matchPhraseQuery("subTitle", keyword);
            boolQueryBuilder.should(sub_title);

            MatchPhraseQueryBuilder content = QueryBuilders
                    .matchPhraseQuery("content", keyword);
            boolQueryBuilder.should(content);
        }

        //开始查询
        builder.query(boolQueryBuilder);
        //从第几页
        builder.from(page-1);
        //每页多少条
        builder.size(size);
        //获取需要的列和不需要的列
        builder.fetchSource(new String[]{"id","titleName", "tags","author","subTitle","content"}, new String[]{});
        // 设置排序规则
        builder.sort("createDate", SortOrder.DESC);
        Map<String, Object> map=elasticSearchUtils.searchListObject(INDEX_NAME,builder, Student.class);
        return Results.success(map);

    }
}
